package com.youlu.campus.service.system.impl;

import com.mongodb.client.result.UpdateResult;
import com.youlu.campus.entity.UserVisitorIpRecord;
import com.youlu.campus.service.system.UserVisitorIpRecordService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
public class UserVisitorIpRecordServiceImpl implements UserVisitorIpRecordService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public boolean create(UserVisitorIpRecord req) {
        req.setId(null);
        req.setCreatedTime(new Date());
        req = mongoTemplate.insert(req);
        if (StringUtils.isNotBlank(req.getId())) {
            return true;
        }
        return false;
    }

    @Override
    public boolean exist(String ip, String userId) {
        Query query = new Query().addCriteria(Criteria.where("ip").is(ip).and("userId").is(userId));
        boolean exist = mongoTemplate.exists(query, UserVisitorIpRecord.class);
        return exist;
    }

    @Override
    public boolean updateUpdatedTime(String id, Date date) {
        Query query = new Query().addCriteria(Criteria.where("id").is(id));
        Update update = new Update();
        update.set("updatedTime", date);
        UpdateResult result = mongoTemplate.updateFirst(query, update, UserVisitorIpRecord.class);
        return result.getModifiedCount() > 0 ? true : false;
    }
}
